package com.joven.shelltest.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;


/**
 * Map+函数式 替代策略模式
 *
 * @Author wzj
 * @Date 2023-08-23 14:46
 **/
@Component
public class StrategyMapFactory {
    @Autowired
    private GrantTypeService grantTypeService;
    private final Map<String, Function<String, String>> grantTypeMap = new HashMap<>();


    @PostConstruct
    public void dispatcherInit() {
        grantTypeMap.put("红包", resourceId -> grantTypeService.redPaper(resourceId));
        grantTypeMap.put("购物券", resourceId -> grantTypeService.shopping(resourceId));
        grantTypeMap.put("qq会员", resourceId -> grantTypeService.QQVip(resourceId));
    }

    public String getResult(String resourceType, String resourceId) {
        return grantTypeMap.entrySet().stream()
                .filter(entry -> entry.getKey().equals(resourceType))
                .map(Map.Entry::getValue)
                .findFirst()
                .orElse(s -> "查询不到该优惠券的发放方式")
                .apply(resourceId);

        //Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType
//        Function<String, String> result = grantTypeMap.get(resourceType);
//        if (result != null) {
//            //传入resourceId 执行这段表达式获得String型的grantType
//            return result.apply(resourceId);
//        }
//        return "查询不到该优惠券的发放方式";
    }
}
